import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/empty_widget.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/components/refresh_footer.dart';
import 'package:kxy_flutter_app/components/refresh_header.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/exam_category.dart';
import 'package:kxy_flutter_app/model/test.dart';
import 'package:kxy_flutter_app/view/examination/template/simple_test_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class TestListView extends StatefulWidget {
  final ExamCategory category;
  TestListView({Key key, this.category}) : super(key: key);

  @override
  _TestListViewState createState() => _TestListViewState();
}

class _TestListViewState extends State<TestListView> {
  Future loadFuture;
  List<Test> testList = new List<Test>();
  RefreshController controller = new RefreshController();

  @override
  void initState() {
    loadFuture = loadList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.category.name)),
      body: FutureBuilder(
        future: loadFuture,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return body();
          }
          return LoadingWidget();
        },
      ),
    );
  }

  Widget body() {
    if (testList.length == 0) {
      return EmptyWidget(onRefresh: loadList);
    }

    return SmartRefresher(
      controller: controller,
      enablePullDown: true,
      enablePullUp: false,
      header: RefreshHeader(),
      footer: RefreshFooter(),
      child: SingleChildScrollView(
        child: SimpleTestWidget(
          testList: testList,
          refresh: loadList,
        ),
      ),
      onRefresh: () async {
        await loadList();
        controller.refreshCompleted();
      },
    );
  }

  Future loadList() async {
    var res = await Http.instance.post('/exam-app/daily/answer/list', params: {
      'cateId': widget.category.id,
      'userId': Auth.instance.userId,
    });

    if (res.code == 200) {
      setState(() {
        testList = (res.data as List).map((e) => Test.fromJson(e)).toList();
      });
    } else {
      Fluttertoast.showToast(msg: res.msg);
    }
  }
}
